import { SubWorldSceneParams } from "../../scripts/SceneDef";
import { GameMgr, GameMode } from "./GameMgr";
import { SubGameMgr } from "./SubGameMgr";
import { UserMgr } from "./UserMgr";
import { WorldMgr } from "./WorldMgr";

export class LobbyGameMgr extends GameMgr {
    private static _inst: LobbyGameMgr = null;
    public static get inst(): LobbyGameMgr {
        if (!this._inst) {
            this._inst = new LobbyGameMgr();
        }
        return this._inst;
    }

    get isConnected() {
        if (WorldMgr.worldConn && WorldMgr.worldConn['__lobby__']) {
            return true;
        }
        return false;
    }


    async connectToLobby() {
        if (this.isConnected) {
            return { isSucc: true };
        }
        let ret = await UserMgr.inst.rpc_QuickPlay('lobby', true);
        if (ret.isSucc) {
            let ret2 = await this.enterWorld({
                ...ret.res,
                uid: UserMgr.inst.uid
            });
            if (ret2.isSucc) {
                WorldMgr.worldConn['__lobby__'] = true;
            }
            return ret2;
        }
        return ret;
    }

    async enterWorld(params: SubWorldSceneParams) {
        SubGameMgr.gameMgr = this;

        this.reset();

        await WorldMgr.doEnterWorld(params);
        let conn = WorldMgr.worldConn;
        this.initNetMsgHandlers(conn);

        let ret = await WorldMgr.ensureConnected();
        if (ret.isSucc) {
            this.gameMode = GameMode.ONLINE;
        }

        return ret;
    }
}